using Godot;

public partial class HoloBridge : Node2D
{
    [Export] public Line2D VisualLine;
    [Export] public StaticBody2D Body;
    [Export] public CollisionShape2D BodyCollider; // StaticBody下的形状

    // 新增引用
    [Export] public Area2D TriggerArea;            // 新增的 Area2D
    [Export] public CollisionShape2D TriggerCollider; // Area2D下的形状

    [Export]
    public string bulid_sfx_res = "res://assets/cc0_sound_effects/320181__dland__hint.wav"; // 建造音效


    [ExportGroup("Appearance")]
    [Export] public float BridgeTriggerWidth = 10.0f; // 桥梁的宽度
    [Export] public float BridgeShaderWidth = 64.0f;

    private PlayerColor _bridgeColor; // 记录当前桥的颜色

    private Tween bridgeTween;

    // 物理层常量 (对应 Project Settings)
    private const int LAYER_RED = 2;
    private const int LAYER_BLUE = 3;
    private const int LAYER_GREEN = 4;

    public override void _Ready()
    {
        // 动态连接信号，防止编辑器漏连
        // 当有物体（玩家）离开区域时触发
        TriggerArea.BodyExited += OnAreaExited;
    }

    public void UpdateBridge(Vector2 start, Vector2 end, PlayerColor colorType)
    {    // 强制开启监控
        TriggerArea.Monitoring = true;

        _bridgeColor = colorType; // 记住颜色

        // 1. 视觉连线
        VisualLine.Points = new Vector2[] { ToLocal(start), ToLocal(end) };

        // 2. 物理层设置 (决定谁撞墙，谁穿透)
        if (colorType == PlayerColor.Red)
        {
            VisualLine.DefaultColor = Colors.Red;
            Body.SetCollisionLayerValue(LAYER_RED, true);
            Body.SetCollisionLayerValue(LAYER_BLUE, false);
            Body.SetCollisionLayerValue(LAYER_GREEN, false);
        }
        else if (colorType == PlayerColor.Blue)
        {
            VisualLine.DefaultColor = Colors.Cyan;
            Body.SetCollisionLayerValue(LAYER_RED, false);
            Body.SetCollisionLayerValue(LAYER_BLUE, true);
            Body.SetCollisionLayerValue(LAYER_GREEN, false);
        }
        else
        {
            VisualLine.DefaultColor = Colors.Lime;
            Body.SetCollisionLayerValue(LAYER_RED, false);
            Body.SetCollisionLayerValue(LAYER_BLUE, false);
            Body.SetCollisionLayerValue(LAYER_GREEN, true);
        }




        // --- 2. 物理层 (Physics) ---
        // 计算几何信息
        Vector2 center = (start + end) / 2.0f;
        float angle = start.AngleToPoint(end);
        float length = start.DistanceTo(end);

        // 设置物理实体的位置和旋转 (与视觉对齐)
        Body.GlobalPosition = center;
        Body.Rotation = angle;

        // 设置检测区域的位置和旋转
        TriggerArea.GlobalPosition = center;
        TriggerArea.Rotation = angle;
        // 4. 调整碰撞形状尺寸

        // A. 物理阻挡 (StaticBody)
        // 长度 = 距离
        // 厚度 = 固定 8px (这是玩家踩的地方)
        if (BodyCollider.Shape is RectangleShape2D bodyRect)
        {
            bodyRect.Size = new Vector2(length, 8);
        }

        // B. 变色检测 (Area2D)
        // 长度 = 距离
        // 厚度 = 固定 12px (稍微比物理层厚一点点，保证接触灵敏)
        // *注意*：不要设成 150px，否则玩家还没碰到桥就变色了，体验会很怪
        if (TriggerCollider.Shape is RectangleShape2D triggerRect)
        {
            triggerRect.Size = new Vector2(length, 12);
        }



        // --- shader更新 ---
        // // 1. 设置 Line2D 点位
        VisualLine.Points = new Vector2[] { ToLocal(start), ToLocal(end) };

        // 获取 Shader Material
        var mat = VisualLine.Material as ShaderMaterial;
        if (mat != null)
        {
            Color targetColor;

            if (colorType == PlayerColor.Red)
            {// 红色
                targetColor = 0.9f * Colors.Red + 0.1f * Colors.Yellow;
            }
            else if (colorType == PlayerColor.Blue)
            {
                // 青色
                targetColor = 0.9f * Colors.Cyan + 0.1f * Colors.White;
            }
            else
            {
                // 绿色
                targetColor = 0.9f * Colors.Lime + 0.1f * Colors.Yellow;
            }

            // 设置 Shader 参数
            mat.SetShaderParameter("base_color", targetColor);



            // 告诉 Shader 桥到底有多长，修正波浪拉伸
            mat.SetShaderParameter("total_length", length);

            // 可选：根据桥的长度动态调整淡出范围
            // 如果桥很短(比如<100px)，淡出范围也要变小，不然整条桥都没了
            float fadeLen = Mathf.Min(60.0f, length * 0.4f);
            mat.SetShaderParameter("fade_length", fadeLen);



            // 5. 显示桥梁

            UpdateAnimation(colorType);
            AudioManager.Instance.PlaySfx(bulid_sfx_res, -5f, 0.2f);

        }


    }

    private void UpdateAnimation(PlayerColor colorType)
    {
        GD.Print(">>> 更新桥梁动画");
        //  宽度动画：从 0 变到 BridgeShaderWidth
        if (bridgeTween != null && bridgeTween.IsValid())
        {
            bridgeTween.Kill();
        }



        VisualLine.Width = 0;
        bridgeTween = CreateTween();
        bridgeTween.TweenProperty(VisualLine, "width", BridgeShaderWidth, 1.5f)
             .SetTrans(Tween.TransitionType.Elastic) // 弹性效果
             .SetEase(Tween.EaseType.Out);

        Color baseColor = Cfg.GetColorValue(colorType);
        VisualLine.DefaultColor = Colors.White; // 瞬间白光
        bridgeTween.Parallel().TweenProperty(VisualLine, "default_color", baseColor, 1.5f);

    }

    public void DisableBridge()
    {
        Visible = false;
        Body.CollisionLayer = 0;
        // 禁用检测区域，防止隐形桥触发变色
        TriggerArea.Monitoring = false;
    }

    // 确保启用时开启检测
    public void EnableBridge()
    {
        Visible = true;
        TriggerArea.Monitoring = true;
    }

    // --- 核心变色逻辑 ---
    public void OnAreaExited(Node2D body)
    {
        // --- 调试代码 START ---
        GD.Print($"有东西离开了区域: {body.Name} | 类型: {body.GetType()}");
        // --- 调试代码 END ---

        if (!Visible) return;

        if (body is PlayerController player)
        {
            // 打印颜色信息，确认条件是否满足
            // GD.Print($"检测到玩家! 玩家颜色: {player.CurrentColor} vs 桥颜色: {_bridgeColor}");

            if (Cfg.CurPlayerColor != _bridgeColor)
            {
                player.SwitchColor(_bridgeColor);

                GD.Print(">>> 变色成功！");
                GD.Print($"桥颜色是: {_bridgeColor}");
                GD.Print($"玩家颜色现在是: {Cfg.CurPlayerColor}");
            }
            else
            {
                GD.Print(">>> 颜色相同，无需变色");
            }
        }
    }
}
